package com.sysolve.betterCity.dao;

import org.hibernate.Criteria;
import org.hibernate.Query;

import com.sysolve.common.HibernateSessionFactory;

public abstract class HibernateDAO {
	public abstract Class getModelClass();
	
	public StringBuffer errors = new StringBuffer();
	public void addError(String error) {
		errors.append(error);
	}
	public String getErrors() {
		return errors.toString();
	}
	
	public boolean save(Object o) {
		try {
			HibernateSessionFactory.getSession().beginTransaction();
			HibernateSessionFactory.getSession().saveOrUpdate(o);
			HibernateSessionFactory.getSession().getTransaction().commit();
		} catch (Exception e) {
			HibernateSessionFactory.getSession().getTransaction().rollback();
			HibernateSessionFactory.closeSession();
			return false;
		} 
		return true;
	}
	
	public boolean delete(Object o) {
		try {
			HibernateSessionFactory.getSession().beginTransaction();
			HibernateSessionFactory.getSession().delete(o);
			HibernateSessionFactory.getSession().getTransaction().commit();
		} catch (Exception e) {
			HibernateSessionFactory.getSession().getTransaction().rollback();
			HibernateSessionFactory.closeSession();
			return false;
		} 
		return true;
	}
	
	public boolean delete(int id) {
		Object o = HibernateSessionFactory.getSession().get(getModelClass(),id);
		if (o!=null) {
			return delete(o);
		} else
			return false;
	}
	
	public java.util.List getList() {
		return HibernateSessionFactory.getSession().createCriteria(getModelClass()).list();
	}
	
	public Query getQuery(String hql) {
		return HibernateSessionFactory.getSession().createQuery(hql);
	}
	
	public Criteria getCriteria() {
		return HibernateSessionFactory.getSession().createCriteria(getModelClass());
	}
	
	public Object get(int id) {
		return HibernateSessionFactory.getSession().get(getModelClass(), id);
	}
	
	public String getIdColumn() {
		return "id";
	}
	
	public Object create() {
		try {
			return getModelClass().newInstance();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
